package com.szwistar.common.comm;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;


class ModbusRtuEncoder implements ProtocolEncoder {
	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		ModbusRtuCmd frame = (ModbusRtuCmd)message;
		out.write(frame.encode());
	}

	@Override
	public void dispose(IoSession session) throws Exception {
	}
}

class ModbusRtuDecoder extends CumulativeProtocolDecoder {
	@Override
	protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
		ModbusRtuAck frame = ModbusRtuAck.decode(in);
		if(frame != null) {
			out.write(frame);
			return true;
		}
		return false;
	}
}

/**
 * MODBUS-RTU 流数据帧编解码器
 */
public class ModbusRtuCodec {
	public static ProtocolCodecFilter newFilter() {
		ModbusRtuDecoder decoder = new ModbusRtuDecoder();
		ModbusRtuEncoder encoder = new ModbusRtuEncoder();
		ProtocolCodecFilter filter = new ProtocolCodecFilter(encoder, decoder);
		return filter;
	}
}
